package com.kasax.cathttp;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.kasax.httpsupport.Call;
import com.kasax.httpsupport.Callback;
import com.kasax.httpsupport.CatHttpClient;
import com.kasax.httpsupport.FormBody;
import com.kasax.httpsupport.Request;
import com.kasax.httpsupport.Response;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

    private CatHttpClient catHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        catHttpClient = new CatHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
    }

    public void handleLogin(View view) {
        FormBody formBody = new FormBody.Builder()
                .add("username", "zzgtest02")
                .add("password", "123456")
                .build();
        Request request = new Request.Builder()
                .url("https://www.wanandroid.com/user/login")
                .post()
                .body(formBody)
                .build();
        parseResponse(request);
    }

    public void handleLoadBanners(View view) {
        try {
            Request request = new Request.Builder()
                    .url("https://wanandroid.com/harmony/index/json")
                    .get()
                    .build();
            parseResponse(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void parseResponse(Request request) {
        Call newCall = catHttpClient.newCall(request);
        newCall.enqueue(new Callback() {
            @Override
            public void onReponse(Response response) {
                Log.i("test", "onReponse: " + response.body().string());
                Toast.makeText(MainActivity.this, response.body().string(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(Request request, IOException exception) {
                Log.i("test", "onFailure: " + exception.getMessage());
            }
        });
    }
}